package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websockettest.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    /**
     * 用户下单
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result orderSubmit(OrdersSubmitDTO dto) {
        //1判断收货地址是否为空
        AddressBook bookMapperById = addressBookMapper.getById(dto.getAddressBookId());
        if (bookMapperById.getDetail()==null){
            return Result.error(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2判断购物车是否为空,先获取用户ID
        Long currentId = BaseContext.getCurrentId();
        List<ShoppingCart> lsit = shoppingCartMapper.lsit(currentId);
        if (lsit==null || lsit.size()==0){
            return Result.error(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //3补充数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setStatus(orders.PENDING_PAYMENT);
        //下单用户id
        orders.setUserId(currentId);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //支付状态 0未支付 1已支付 2退款
        orders.setPayStatus(orders.UN_PAID);
        //手机号
        orders.setPhone(bookMapperById.getPhone());
        //地址
        orders.setAddress(bookMapperById.getDetail());
        //收货人
        orders.setConsignee(bookMapperById.getConsignee());
        //4插入订单表
        orderMapper.indest(orders);
        //5把购物车的数据批量插入订单明细表
        List<OrderDetail> orderDetailList =new ArrayList<>();//创建一个订单明细表集合
        for (ShoppingCart shoppingCart : lsit) {//遍历
            //new一个订单明细表
            OrderDetail detail = new OrderDetail();
            //映射
            BeanUtils.copyProperties(shoppingCart,detail);
            //获取订单ID
            detail.setOrderId(orders.getId());
            //订单明细表添加到集合中
            orderDetailList.add(detail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //6清空购物车
        shoppingCartMapper.clean(currentId);
        //7返回封装数据
       OrderSubmitVO orderSubmitVO=OrderSubmitVO.builder()
               .id(orders.getId())
               .orderTime(orders.getOrderTime())
               .orderAmount(orders.getAmount())
               .orderNumber(orders.getNumber())
               .build();
        return Result.success(orderSubmitVO);
    }
    /**
     * 历史查询
     *
     * @param dto
     * @return
     */
    @Override
    public Result page(OrdersPageQueryDTO dto) {
        //非空判断
        if(dto.getPage()==null){
        dto.setPage(1);
        }
        if (dto.getPageSize()==null){
            dto.setPageSize(10);
        }
        //分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //获取请求中的用户ID放入dto中
        Long currentId = BaseContext.getCurrentId();
        dto.setUserId(currentId);
        //调用OrdersMapper的page方法放入分页工具的Result集合中
        Page<Orders> orders = orderMapper.pageFind(dto);
        //将page中的数据放入订单表集合中
        List<Orders> result = orders.getResult();
        //创建集合装订单详细表乏型为OrdersVO
        ArrayList<OrderVO> orderVOS = new ArrayList<>(orders.size());
        //遍历
        for (Orders orders1 : result) {
            //new一个OrdersVO类装单个的订单详细表数据
            OrderVO orderVO = new OrderVO();
            //Orders映射到OrdersVO
            BeanUtils.copyProperties(orders1,orderVO);
            //调用orderDetailMapper方法查询所有订单详细表
            List<OrderDetail> orderDetailList = orderDetailMapper.getById(orders1.getId());
            //把orderDetailMapper方法查询所有订单详细表放入OrdersVO类中的OrderDetailList集合中
            orderVO.setOrderDetailList(orderDetailList);
            //进行封装到集合中
            orderVOS.add(orderVO);
         }
        //封装到PageResult类中返回
        PageResult pageResult = new PageResult();
        pageResult.setRecords(orderVOS);
        pageResult.setTotal(orders.getTotal());
        //返回
        return Result.success(pageResult);

    }

    /**
     * 用户催单
     *
     * @param id
     * @return
     */
    @Override
    public Result reminder(Long id) {
        //非空判断
        if (id==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //调用mapper查询
        Orders order = orderMapper.getById(id);
        if (order==null){
         return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }
        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + order.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        //判断是否存在
        return Result.success();
    }

    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result Anotherorder(Long id) {
        //非空判断
        if (id==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //根据ID调用orderdetailmapper方法进行查询
        List<OrderDetail> orderDetails = orderDetailMapper.getById(id);
        //判断查询结果
        if (orderDetails!=null){
            //为真把查询数据添加到购物车
            for (OrderDetail orderDetail : orderDetails) {
                ShoppingCart shoppingCart = new ShoppingCart();
                BeanUtils.copyProperties(orderDetail,shoppingCart);
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCart.setUserId(BaseContext.getCurrentId());
                shoppingCartMapper.insert(shoppingCart);
            }
        }
        //返回
        return Result.success();
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public Result orderDetailFind(Long id) {
        //非空判断
        if (id==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //调用方法订单中查询数据判断是否为空
        Orders mapperById = orderMapper.getById(id);
        //为空返回数据
        if (mapperById==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //为真
        //复制到OrderVO中
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(mapperById,orderVO);
        //查询订单详细表数据
        List<OrderDetail> byId = orderDetailMapper.getById(id);
        //写入到订单详细表的OrderDetailList集合中
        orderVO.setOrderDetailList(byId);
        return Result.success(orderVO);
    }

    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    public Result cancel(Long id) {
        //非空判断
        if (id==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //查询订单是否为空
        Orders mapperById = orderMapper.getById(id);
        if (mapperById!=null){
        mapperById.setStatus(Orders.CANCELLED);
        orderMapper.update(mapperById);
        }
        return Result.success();
    }
    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理（收货地址为空、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.lsit(shoppingCart.getUserId());
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.indest(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shoppingCartMapper.clean(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getByUserId(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //创建一个map进行管理端与服务器沟通
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
    /**
     * 管理端订单搜索
     *
     * @param dto
     * @return
     */
    @Override
    public Result pageAdmin(OrdersPageQueryDTO dto) {
        //非空判断
        if(dto.getPage()==null){
            dto.setPage(1);
        }
        if (dto.getPageSize()==null){
            dto.setPageSize(10);
        }
        //分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //调用mapper方法吧数据放入page中
        Page<Orders> orders = orderMapper.pageFind(dto);
        //获取page工具中的订单数据
        List<Orders> result = orders.getResult();
        //创建一个集合装所有订单详细
        List<OrderVO> orderVOS=new ArrayList<>();
        //字符串拼接
        StringBuilder stringBuilder=new StringBuilder();
        for (Orders orders1 : result) {
            OrderVO orderVO = new OrderVO();
            //复制
            BeanUtils.copyProperties(orders1,orderVO);
            //查询订单详细
            List<OrderDetail> byId = orderDetailMapper.getById(orders1.getId());
            //进行判断
            for (OrderDetail orderDetail : byId) {
                stringBuilder.append(orderDetail.getName()).append(":").append("数量为:")
                .append(orderDetail.getNumber()).append("价格:").append(orderDetail.getAmount()).append(",");
            }
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
            orderVO.setOrderDishes(stringBuilder.toString());
            orderVOS.add(orderVO);
        }
        //封装
        PageResult pageResult=new PageResult();
        pageResult.setTotal(orders.getTotal());
        pageResult.setRecords(orderVOS);
        //返回
        return Result.success(pageResult);
    }

    /**
     * 管理端查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public Result details(Long id) {
        //非空判断
        if(id==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //根据ID查询订单是否存在获取订单信息
        Orders mapperId = orderMapper.getId(id);
        if(mapperId==null){
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }
            //调用mapper方法查询订单详细
            List<OrderDetail> byId = orderDetailMapper.getById(id);
            //写入OrderVO
            OrderVO orderVO = new OrderVO();
            orderVO.setOrderDetailList(byId);
            //映射到Orders中
            BeanUtils.copyProperties(mapperId,orderVO);

        //返回
        return Result.success(orderVO);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public Result statistics() {
        //调用mapper方法查询个个状态数量
        //待接单数量
        Integer toBeConfirmedCount = orderMapper.getStatistics(Orders.TO_BE_CONFIRMED);
        //待派送数量
        Integer confirmedCount = orderMapper.getStatistics(Orders.CONFIRMED);
        //派送中数量
        Integer deliveryCount = orderMapper.getStatistics(Orders.DELIVERY_IN_PROGRESS);
        //封装
        OrderStatisticsVO vo = OrderStatisticsVO.builder()
                .confirmed(confirmedCount)
                .deliveryInProgress(deliveryCount)
                .toBeConfirmed(toBeConfirmedCount)
                .build();
        //返回
        return Result.success(vo);


    }

    /**
     * 取消订单
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result cancelOrder(OrdersCancelDTO dto) {
        //非空判断
        if (dto.getId()==null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //根据ID查询是否存在
        Orders orders = orderMapper.getId(dto.getId());
        if (orders==null){
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }
//        //支付状态
//        Integer payStatus = orders.getPayStatus();
//        if (payStatus == 1) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    orders.getNumber(),
//                    orders.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }
        //补充数据
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(dto.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
        //返回
        return Result.success();
    }

    /**
     * 接单
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result confirm(OrdersConfirmDTO dto) {
        if(dto.getId()==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        Orders mapperId = orderMapper.getId(dto.getId());
        if (mapperId==null){
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }
        mapperId.setStatus(Orders.CONFIRMED);
        //调用mapper进行修改
        orderMapper.update(mapperId);
        //返回
        return Result.success();
    }

    /**
     * 拒单
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result rejection(OrdersRejectionDTO dto) {
        //非空判断
        if(dto.getId()==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //查询是否存在订单
        Orders orders = orderMapper.getId(dto.getId());
        if (orders==null){
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }
//        //支付状态
//        Integer payStatus = orders.getPayStatus();
//        if (payStatus == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    orders.getNumber(),
//                    orders.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        //调用mapper进行修改
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setRejectionReason(dto.getRejectionReason());
        orderMapper.update(orders);
        //返回
        return Result.success();
    }

    /**
     * 派送订单
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result delivery(Long id) {
        //非空判断
        if(id==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //查询订单是否存在
        Orders orders = orderMapper.getId(id);
        //订单不存在且状态不为已接单
        if (orders==null || !orders.getStatus().equals(Orders.CONFIRMED)){
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }
        //修改状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
        //返回
        return Result.success();
    }

    /**
     * 完成订单
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result complete(Long id) {
        //非空判断
        if(id==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //查询订单是否存在
        Orders orders = orderMapper.getId(id);
        //订单不存在且状态不为完成
        if (orders==null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
        return Result.success();
    }
}
